package se.topshelf.golftracker.core.domain;

import org.hibernate.annotations.Sort;
import org.hibernate.annotations.SortType;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.text.MessageFormat;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 *
 */
@Entity
@Table(name = "ClubModel")
public class ClubModel extends BaseEntity implements Comparable<ClubModel> {
    @NotNull
    @ManyToOne
    @JoinColumn(name = "manufacturerId")
    Manufacturer manufacturer;

    @NotNull
    private String name;

    @OneToMany(mappedBy = "clubModel", cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
    @Sort(type = SortType.NATURAL)
    private SortedSet<Club> clubs = new TreeSet<Club>();

    public ClubModel() {
    }

    public ClubModel(Manufacturer manufacturer, String name) {
        this.manufacturer = manufacturer;
        this.name = name;
    }

    public Manufacturer getManufacturer() {
        return manufacturer;
    }

    public void setManufacturer(Manufacturer manufacturer) {
        this.manufacturer = manufacturer;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public SortedSet<Club> getClubs() {
        return clubs;
    }

    public void addClub(Club club){
        if(clubs.contains(club)){
            throw new IllegalArgumentException(MessageFormat.format(ILLEGAL_TO_REMOVE_ERROR_MESSAGE, club, this));
        }
        club.setClubModel(this);
        clubs.add(club);
    }

    public void setClubs(SortedSet<Club> clubs) {
        this.clubs = clubs;
    }

    public int compareTo(ClubModel o) {
        int manufacturerCompare = manufacturer.compareTo(o.getManufacturer());
        if(manufacturerCompare == 0){
            return name.compareTo(o.getName());
        }
        return manufacturerCompare;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ClubModel clubModel = (ClubModel) o;

        if (!name.equals(clubModel.name)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return name.hashCode();
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("ClubModel");
        sb.append("{manufacturer=").append(manufacturer);
        sb.append(", name='").append(name).append('\'');
        sb.append('}');
        return sb.toString();
    }
}
